package com.taxshare.seller.service;


import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.taxshare.freemark.utils.FreemarkUtil;
import com.taxshare.seller.constant.CodeConstant;
import com.taxshare.seller.entity.EquipmentEntity;
import com.taxshare.seller.entity.RemainderInvoiceEntity;
import com.taxshare.seller.entity.StockDetailEntity;
import com.taxshare.seller.mapper.RemainderInvoiceMapper;
import com.taxshare.seller.util.InvoiceHelper;
import com.taxshare.seller.util.Xml2Map;
import com.taxshare.seller.view.dto.InterfaceDTO;
import com.taxshare.seller.view.dto.SellerInvoiceDTO;
import com.taxshare.seller.view.vo.SellerInvoiceVO;
import com.taxshare.tools.token.UserInfoUtil;
import com.taxshare.tools.util.Base64Util;
import lombok.extern.slf4j.Slf4j;

import org.apache.commons.collections.MapUtils;
import org.aspectj.apache.bcel.classfile.Code;
import org.omg.IOP.Codec;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.StrUtil;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.taxshare.mybatis.pager.PageHelp;
import com.taxshare.mybatis.pager.PageRequest;
import com.taxshare.mybatis.utils.DozerBeanUtil;
import com.taxshare.response.beans.Response;
import com.taxshare.seller.entity.BlankInvoiceCollctionEntity;
import com.taxshare.seller.mapper.BlankInvoiceCollctionMapper;
import com.taxshare.seller.remote.ApiClientService;
import com.taxshare.seller.util.sst.IntJsonUtil;
import com.taxshare.seller.view.dto.BlankInvoiceCollctionDTO;
import com.taxshare.seller.view.vo.BlankInvoiceCollctionVO;
import com.taxshare.tools.util.UUIDUitl;

/**
 * @author YANG
 * @date 2021/3/18
 * @Description:空白发票领购
 */
@Service
@Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.READ_COMMITTED)
@Slf4j
public class BlankInvoiceCollctionService extends ServiceImpl<BlankInvoiceCollctionMapper, BlankInvoiceCollctionEntity> {

    @Autowired
    ApiClientService apiClientService;

    @Autowired
    SellerCommonService sellerCommonService;

    @Autowired
    EquipmentService equipmentService;

    @Autowired
    StockDetailService stockDetailService;

    @Value("${zzsfp.url}")
    private String zzsfpUrl;

    @Autowired
    RemainderInvoiceMapper remainderInvoiceMapper;

    /**
     * 空白发票领购【空白发票领购查询】
     *
     * @param query
     * @return
     */
    public Response blankInvoiceCollectionQuery(PageRequest<BlankInvoiceCollctionDTO> query) {
        QueryWrapper<BlankInvoiceCollctionEntity> queryWrapper = new QueryWrapper();
        BlankInvoiceCollctionDTO blankInvoiceCollctionDTO = query.getInfo();
        String pickUpDateStart = blankInvoiceCollctionDTO.getPickUpDateStart();
        String pickUpDateEnd = blankInvoiceCollctionDTO.getPickUpDateEnd();
        if (StrUtil.isNotBlank(blankInvoiceCollctionDTO.getSellerName())) {
            queryWrapper.like("seller_tax_no", blankInvoiceCollctionDTO.getSellerTaxNo());
        }
        if (StrUtil.isNotBlank(blankInvoiceCollctionDTO.getInvoiceType())) {
            queryWrapper.eq("invoice_type", blankInvoiceCollctionDTO.getInvoiceType());
        }
        if (StrUtil.isNotBlank(blankInvoiceCollctionDTO.getTaxPanelNo())) {
            queryWrapper.eq("tax_panel_no", blankInvoiceCollctionDTO.getTaxPanelNo());
        }
        if (StrUtil.isNotBlank(pickUpDateStart) && StrUtil.isNotBlank(pickUpDateEnd)) {
            queryWrapper.between("pick_up_date", pickUpDateStart, pickUpDateEnd);
        }
        queryWrapper.orderByDesc("create_time");
        IPage<BlankInvoiceCollctionVO> result = PageHelp.siamplePage(this, queryWrapper, query.getPage(), BlankInvoiceCollctionVO.class);
        return Response.success(result);
    }


    //领购成功发票插入空白发票表，存在则更新，否则直接插入
    private void insertInvoice(List<Map> sstDataList) {
        // 根据盘号、发票类型,发票代码、发票起号、领购日期查询库中是否已存在
        if (CollUtil.isNotEmpty(sstDataList)) {
            for (Map map : sstDataList) {
                String invoiceType = MapUtil.getStr(map, "fplxdm");
                String invoiceCode = MapUtil.getStr(map, "fpdm");
                QueryWrapper<BlankInvoiceCollctionEntity> queryWrapper = new QueryWrapper();
                queryWrapper.eq("invoice_type", invoiceType);
                queryWrapper.eq("invoice_code", invoiceCode);
                List<BlankInvoiceCollctionEntity> list = this.list(queryWrapper);
                if (list != null && list.size() > 0) {
                    BlankInvoiceCollctionEntity blankInvoiceCollctionEntity = list.get(0);
                    blankInvoiceCollctionEntity.setInvoiceSheet(MapUtils.getString(map, "fpfs"));
                    blankInvoiceCollctionEntity.setInvoiceStartNo(MapUtils.getString(map, "qshm"));
                    blankInvoiceCollctionEntity.setInvoiceNoEnd(getInvoiceNoEnd(map));
                    blankInvoiceCollctionEntity.setPickUpDate(MapUtils.getString(map, "lgrq"));
                    baseMapper.updateById(blankInvoiceCollctionEntity);
                } else {
                    BlankInvoiceCollctionEntity blankInvoiceCollctionEntity = new BlankInvoiceCollctionEntity();
                    blankInvoiceCollctionEntity.setUuid(UUIDUitl.UUID32(false));
                    blankInvoiceCollctionEntity.setSellerName("");
                    blankInvoiceCollctionEntity.setSellerTaxNo("");
                    blankInvoiceCollctionEntity.setInvoiceType(invoiceType);
                    blankInvoiceCollctionEntity.setInvoiceCode(invoiceCode);
                    blankInvoiceCollctionEntity.setInvoiceStartNo(MapUtils.getString(map, "qshm"));
                    blankInvoiceCollctionEntity.setInvoiceNoEnd(getInvoiceNoEnd(map));
                    blankInvoiceCollctionEntity.setPickUpDate(MapUtils.getString(map, "lgrq"));
                    blankInvoiceCollctionEntity.setInvoiceSheet(MapUtils.getString(map, "fpfs"));
                    baseMapper.insert(blankInvoiceCollctionEntity);
                }
            }
        }
    }

    //根据发票份数和起始号码计算发票止号
    private String getInvoiceNoEnd(Map map) {
        int invoiceNoStart = Integer.parseInt(MapUtils.getString(map, "qshm", "0"));
        int invoiceNumber = Integer.parseInt(MapUtils.getString(map, "fpfs", "0"));
        return String.valueOf(invoiceNoStart + invoiceNumber);
    }

    /**
     * 空白发票作废
     *
     * @param sellerInvoiceVO
     * @return
     */
    public Response blankInvoiceCancel(SellerInvoiceVO sellerInvoiceVO) throws Exception {
        Response res = new Response();
        //获取开票设备 A9对应明源开票 其他则税神通开票
        String sellerTaxNo = sellerInvoiceVO.getSellerTaxNo();
        String invoiceCode = sellerInvoiceVO.getInvoiceCode();
        String invoiceNoStart = sellerInvoiceVO.getInvoiceNoStart();
        EquipmentEntity equipmentEntity = equipmentService.getOne(new QueryWrapper<EquipmentEntity>().eq("seller_tax_no", sellerTaxNo).eq("disable", "1"));
        if (null == equipmentEntity) {
            res.setCode("T0001");
            res.setMsg("同步失败，该纳税人识别号对应的设备未添加或开启，请检查！");
            return res;
        }
        //设备类型
        String equipmentMode = equipmentEntity.getEquipmentMode();
        if (StrUtil.isBlank(sellerInvoiceVO.getSellerWhiteNum())) {
            return Response.error("SEL_107");
        }
//        stockDetailService.syncStockDetail(sellerTaxNo);
        RemainderInvoiceEntity remainderInvoiceEntity = remainderInvoiceMapper.selectOne(new QueryWrapper<RemainderInvoiceEntity>().eq("seller_tax_no", sellerTaxNo)
                .eq("invoice_code",invoiceCode).eq("invoice_no_start",invoiceNoStart));
        if (null == remainderInvoiceEntity) {
            return Response.error("SEL_042");
        }
        int noStart = Integer.valueOf(remainderInvoiceEntity.getInvoiceNoStart());
        String codeStart = remainderInvoiceEntity.getInvoiceCode();
        int num = Integer.valueOf(remainderInvoiceEntity.getInvoiceSheet());
        if (num == 0 || num < Integer.valueOf(sellerInvoiceVO.getSellerWhiteNum())) {
            return Response.error("SEL_043");
        }
        for (int i = 0; i < Integer.valueOf(sellerInvoiceVO.getSellerWhiteNum()); i++) {
            if (CodeConstant.A9.equals(equipmentMode)) {
                res = blankInvoiceCancelA9(sellerInvoiceVO);
            } else {
                if (CodeConstant.JSP.equals(equipmentMode)) {
                    sellerInvoiceVO.setInvoiceType(IntJsonUtil.checkFplxdm("0", sellerInvoiceVO.getInvoiceType()));
                }
                res = blankInvoiceCancelSST(sellerInvoiceVO, equipmentEntity, String.valueOf(noStart), codeStart);
                if(!CodeConstant.T0000.equals(res.getCode())){
                    return res;
                }
                noStart += 1;
//                codeStart += 1;
            }
        }
        //调用余票同步接口
        Response syncResponse = stockDetailService.syncInventoryInvoiceSST(equipmentEntity,CodeConstant.COMM_CODE_1);
        if (CodeConstant.T0000.equals(syncResponse.getCode())) {
            return Response.success();
        }else {
            return Response.error("SEL_SYNC_006");
        }
    }

    /**
     * A9空白发票作废
     *
     * @param sellerInvoiceVO
     * @return
     */
    public Response blankInvoiceCancelA9(SellerInvoiceVO sellerInvoiceVO) throws Exception {
        String url = zzsfpUrl + "busiInterface";
        String interfaceCode = "EI.KBFPZF.U.EC.INTRA";
        String fplx = InvoiceHelper.transFplxdm(sellerInvoiceVO.getInvoiceType());
        sellerInvoiceVO.setInvoiceType(fplx);
        String ykInvoiceData = FreemarkUtil.getTemplateObj("/kbCancelInvoice.ftl", sellerInvoiceVO);
        String xmlData = InvoiceHelper.getXmlData(ykInvoiceData, interfaceCode, sellerInvoiceVO.getSellerTaxNo(), null);
        InterfaceDTO interfaceDTO = new InterfaceDTO();
        interfaceDTO.setXmlData(xmlData);
        interfaceDTO.setUrl(url);
/*        Response response = apiClientService.callSales(interfaceDTO);
        if ("T0000".equals(response.getCode())) {
            syncBlankInvoice(sellerInvoiceVO.getInvoiceType());
        } else {
            return Response.error("空白发票作废失败：" + response.getMsg());
        }*/
        return Response.success();
    }

    /**
     * 税神通空白发票作废
     *
     * @param sellerInvoiceVO
     * @return
     */
    public Response blankInvoiceCancelSST(SellerInvoiceVO sellerInvoiceVO, EquipmentEntity equipmentEntity, String invoiceNo, String invoicecode) {
        String json = IntJsonUtil.cancelBlankInvoices(equipmentEntity.getAppid(),
                sellerInvoiceVO.getSellerTaxNo(), sellerInvoiceVO.getInvoiceType(),
                equipmentEntity.getEquipmentMode(), invoicecode, invoiceNo, UserInfoUtil.getUserNickName());
        SellerInvoiceDTO sellerInvoiceDTO = new SellerInvoiceDTO();
        sellerInvoiceDTO.setBw(json);
        Response response = apiClientService.callSST(sellerInvoiceDTO);
        String result = (String) response.getData();
        JSONObject jsonObject = (JSONObject) JSON.parse(result);
        String code = jsonObject.getString("code");
        String msg = jsonObject.getString("msg");
        if (CodeConstant.THIRD_PARTY_SUCCESS.equals(code)) {
            return Response.success();
        } else {
            return Response.error(CodeConstant.T0001,msg);
        }
    }
}
